package com.beiing.tianshuai.tianshuai.dongtai;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.CommentReplyAll_RVAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.dongtai.presenter.CommentReplyPresenter;
import com.beiing.tianshuai.tianshuai.dongtai.view.CommentReplyViewImpl;
import com.beiing.tianshuai.tianshuai.entity.DynamicDetailBean;
import com.beiing.tianshuai.tianshuai.fragment.EmotionCompleteFragment;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.util.GlobalOnItemClickManagerUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 回复详情页面
 * Created by LZQ on 2017/8/21.
 */

public class CommentReplyActivity extends BaseActivity implements CommentReplyViewImpl,View.OnClickListener{

    private final String TAG = "CommentReplyActivity";
    private CommentReplyAll_RVAdapter mAdapter;
    private List<DynamicDetailBean.DataBean.CommentBean.ReplyBean> replyBeanList;
    private DynamicDetailBean.DataBean.CommentBean commentBean;
    private CommentReplyPresenter mPresenter;
    private InputMethodManager imm;
    private int comment_position;
    private String did;                 //动态id
    private String cid;                 //评论id
    private String form_uid;            //自己id
    private String to_uid;              //评论发布人id
    private String touid;               //回复发布人id
    private String registration_id;
    private EmotionCompleteFragment emotionCompleteFragment;
    private boolean emotionLayoutShow;      //表情面板是否显示
    private GlobalOnItemClickManagerUtils globalOnItemClickManager;

    @BindView(R.id.toolbar_iv_back)
    ImageView toolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView toolbarTvTitle;
    @BindView(R.id.toolbar_center_title)
    TextView toolbarCenterTitle;
    @BindView(R.id.reply_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.comment_reply_edit)
    EditText mEditText;
    @BindView(R.id.comment_reply_send)
    TextView mSendText;
    @BindView(R.id.iv_face)
    ImageView ivFace;
    @BindView(R.id.iv_keyboard)
    ImageView ivKeyBoard;
    @BindView(R.id.fl_emotionview_main)
    FrameLayout mEmotionLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_comment_reply;
    }

    @Override
    protected void init() {
        initTitle();
        initData();
        initPresenter();
        initRecyclerView();
        initListener();
        initEmotionMainFragment();
    }

    private void initEmotionMainFragment() {
        globalOnItemClickManager = GlobalOnItemClickManagerUtils.getInstance(mContext);
        globalOnItemClickManager.attachToEditText(mEditText);
        emotionCompleteFragment = new EmotionCompleteFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fl_emotionview_main, emotionCompleteFragment);
        transaction.commit();
    }

    private void initPresenter() {
        mPresenter = new CommentReplyPresenter(this);
        mPresenter.getReply(form_uid, did);
    }

    private void initTitle() {
        toolbarIvBack.setVisibility(View.VISIBLE);
        toolbarIvBack.setOnClickListener(this);
        toolbarTvTitle.setVisibility(View.GONE);
        toolbarCenterTitle.setVisibility(View.VISIBLE);
        toolbarCenterTitle.setText("全部回复");
    }

    private void initData() {
        Intent intent = this.getIntent();
        comment_position = intent.getIntExtra("position", 0);
        commentBean = (DynamicDetailBean.DataBean.CommentBean) intent.getSerializableExtra("reply");
//        replyBeanList = commentBean.getReply();
        did = commentBean.getAid();
        cid = commentBean.getId();
        form_uid = SPUtils.getString(mContext, "uid", null);
        to_uid = commentBean.getUid();
        registration_id = commentBean.getUid();

        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    private void initRecyclerView() {
        replyBeanList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mAdapter = new CommentReplyAll_RVAdapter(mContext, replyBeanList);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mAdapter);

        /**
         * onTextClick方法，点击到了指定文字才会调用
         */
        mAdapter.setTextClickListener(new CommentReplyAll_RVAdapter.TextClickListener() {
            @Override
            public void onTextClick(View view, int itemposition, int tvposition) {
                switch (tvposition){
                    case 1:
                        Intent intent = new Intent();
                        intent.setClass(mContext, NewPersonalIndexActivity.class);
                        intent.putExtra("uid", replyBeanList.get(itemposition).getFormUid());
                        startActivity(intent);
                        break;
                    case 2:
                        Intent intent1 = new Intent();
                        intent1.setClass(mContext, NewPersonalIndexActivity.class);
                        intent1.putExtra("uid", replyBeanList.get(itemposition).getToUid());
                        startActivity(intent1);
                        break;
                    case 3:
                        //显示删除对话框
                        showDeleteDialog(itemposition);
                        break;
                }
            }
        });

        /**
         * onItemClick方法 只要点击到了条目就会调用
         */
        mAdapter.setOnItemClickListener(new CommentReplyAll_RVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int childPosition) {
                int i = replyBeanList.size() - childPosition - 1;
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                mEditText.setFocusable(true);
                mEditText.setFocusableInTouchMode(true);
                mEditText.requestFocus();
                mEditText.setHint("回复" + replyBeanList.get(i).getFName().toString());
                touid = replyBeanList.get(i).getFormUid();
                LogUtils.i(replyBeanList.get(i).getFName().toString(), TAG);
            }
        });
    }

    private void showDeleteDialog(final int itemPosition) {
        CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                "确定要删除这条回复么？",
                new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm){
                            mPresenter.deleteReply(form_uid, replyBeanList.get(itemPosition).getId(), itemPosition);
                            showShortText("删除成功");
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                });
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    public void initListener(){
        mSendText.setOnClickListener(this);

        mEditText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mEditText.setFocusable(true);
                mEditText.setFocusableInTouchMode(true);
                mEditText.requestFocus();
                mEmotionLayout.setVisibility(View.GONE);
                return false;
            }
        });

        mSendText.setClickable(false);

        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0 && !"".equals(s.toString().trim())){     //有文字内容
                    mSendText.setBackgroundResource(R.drawable.publish_blue);
                    mSendText.setClickable(true);
                } else {
                    mSendText.setBackgroundResource(R.drawable.publish_gray);        //没有文字内容
                    mSendText.setClickable(false);
                }
            }
        });

        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mEditText.setFocusable(false);
                mEditText.setHint("说几句...");
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.GONE);
                emotionLayoutShow = false;
                return false;
            }
        });

        ivFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivFace.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.VISIBLE);
                emotionLayoutShow = true;
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.VISIBLE);
            }
        });

        ivKeyBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEmotionLayout.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                emotionLayoutShow = false;
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                mEditText.setFocusable(true);
                mEditText.setFocusableInTouchMode(true);
                mEditText.requestFocus();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.toolbar_iv_back:
                finish();
                break;
            case R.id.comment_reply_send:
                if (TextUtils.isEmpty(mEditText.getText()) || "".equals(mEditText.getText().toString().trim())){

                } else {
                    if (mEditText.getHint().equals("说几句...")){
                        try {
                            String contentUTF8 = URLEncoder.encode(mEditText.getText().toString(),"UTF-8");
                            mPresenter.addReply(did, cid, form_uid, to_uid, contentUTF8, registration_id);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            String contentUTF8 = URLEncoder.encode(mEditText.getText().toString(), "UTF-8");
                            mPresenter.addReply(did, cid, form_uid, touid, contentUTF8, touid);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                    mEditText.clearFocus();
                    mEditText.setText("");
                }
        }
    }

    @Override
    public void showReply(DynamicDetailBean dynamicDetailBean) {
        List<DynamicDetailBean.DataBean.CommentBean.ReplyBean> replyBeen = dynamicDetailBean.getData().getComment().get(comment_position).getReply();
        replyBeanList.clear();
        replyBeanList.addAll(replyBeen);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void removeReply(int position) {
        mAdapter.removeItem(position);
        mAdapter.notifyDataSetChanged();
    }
}
